package com.changgou.controller;

import com.changgou.entity.Page;
import com.changgou.pojo.SkuInfo;
import com.changgou.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping("/search")
public class SearchController {

    @Autowired
    private SearchService searchService;

    @GetMapping
    @ResponseBody
    public Map search(@RequestParam Map<String, String> searchMap) {

        Map searchResult = searchService.search(searchMap);
        return searchResult;
    }

    @GetMapping("/list")
    public String list(@RequestParam Map<String, String> searchMap, Model model) {

        Map resultMap = searchService.search(searchMap);
        model.addAttribute("resultMap", resultMap);
        model.addAttribute("searchMap", searchMap);

        Page<SkuInfo> page = new Page<>(Long.parseLong(resultMap.get("total").toString()),
                Integer.parseInt(String.valueOf(resultMap.get("pageNum"))),Page.pageSize);
        model.addAttribute("page",page);

        StringBuilder url = new StringBuilder("/search/list");
        if (searchMap != null && searchMap.size() > 0) {
            url.append("?");
            for (String key : searchMap.keySet()) {
                if (!"sortRule".equals(key) && !"sortFiled".equals(key) && !"pageNum".equals(key)) {
                    url.append(key).append("=").append(searchMap.get(key)).append("&");
                }
            }
            String urlString = url.toString();
            urlString = urlString.substring(0, urlString.length() - 1);
            model.addAttribute("url", urlString);
        } else {
            model.addAttribute("url",url.toString());
        }

        return "search";
    }

}
